//
//  TwoPicturesViewController.m
//  JinMaJiaDemo
//
//  Created by GripMeMory on 15/9/8.
//  Copyright (c) 2015年 GripMeMory. All rights reserved.
//

#import "HomePageViewController.h"
#import "TableViewDataSource.h"

#import "UIView+Sizes.h"
#import <MJRefresh.h>

#import "HomePageSearchViewController.h"
#import "LoginViewController.h"

#import "AdModel.h"
#import "JMJBaseCollectionViewCell.h"

#import "PopSelectionCell.h"

#import "MessageCenterViewController.h"

#import <SDCycleScrollView/SDCycleScrollView.h>

#import "HomePageCollectionViewCell.h"
#import "HomePageCollectionReusableView.h"

#import "OfferSiteViewController.h"

#import "ChannelViewController.h"


static NSString * const tableViewCellName = @"TwoPicturesCell";
static NSString * const SelectionCellName = @"SelectionCell";
static NSString *homepageCollectionCellName = @"HomePageCollectionCell";
static NSString *homepageCollectionReusableName = @"HomePageReusabelView";

#define kCollectionViewWidth (UISCREENWIDTH / 3 - 24)

#define kNavigationBarHeight ([[[UIDevice currentDevice] systemVersion] intValue] >= 7.0 ? 64 : 44)

//cell的高度
static CGFloat const kHomePageCellHeight = 520 / 2;

@interface HomePageViewController () <UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate, SDCycleScrollViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>

{
    WYPopoverController *_popover;
    NSArray *_array;
    NSArray *_selectionArr;
    NSMutableArray *_dataArr;
    UITableViewController *_tbc;
    UITableViewController *_tbc2;
    SDCycleScrollView *_cycleView;
    UICollectionView *_collectionView;
}

@property (nonatomic, strong) TableViewDataSource *dataSource;

@end

@implementation HomePageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _dataArr = [NSMutableArray arrayWithCapacity:10];
    [self fakeValue];
//    [self loadAdView];
    [self loadCycleScrollView];
    [self customeUI];
    [self setupCollectionView];
    //custom the navigationbar
    [self customNavBar];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Custom Nav

/**
 *  @author GripMeMory, 15-12-01 14:12:01
 *
 *  custom the navigation bar
 */
- (void)customNavBar{
    
    self.title = @"首页";
    UIImage *normalImage = [[UIImage imageNamed:@"首页1.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIImage *selectedImage = [[UIImage imageNamed:@"首页.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationController.tabBarItem.image = normalImage;
    self.navigationController.tabBarItem.selectedImage = selectedImage;
    
    //Left bar button item
    UIBarButtonItem *bbi = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"类目"] style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonItemClick:)];
    bbi.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = bbi;
    
    //titleView
    UIImageView *titleView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    UIImage *titleImage = [UIImage imageNamed:@"搜索.png"];
    titleView.image = titleImage;
    titleView.clipsToBounds = YES;
    titleView.contentMode = UIViewContentModeScaleToFill;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(titleViewClick:)];
    [titleView addGestureRecognizer:tap];
    titleView.userInteractionEnabled = YES;
    self.navigationItem.titleView = titleView;
    
    //right bar button item
    UIBarButtonItem *bbi2 = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"消息"] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemClick:)];
    bbi2.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = bbi2;
    
    self.tabBarController.tabBarItem.badgeValue = @"4";
    
    //Show the tab bar
    self.tabBarController.tabBar.hidden = NO;
}

#pragma mark - Custom UserInterface

/**
 *  @author GripMeMory, 15-12-01 14:12:47
 *
 *  Custom the User interface
 */
- (void)customeUI{
    _array  = @[@"股权转让", @"实物资产", @"公共资源", @"司法拍卖", @"网络采购"];
    _selectionArr = @[@"股权转让", @"实物资产", @"公共资源", @"司法拍卖", @"网络采购"];
//    _dataArr = [self fakeSource];
}

- (void)loadCycleScrollView{
    NSArray *array = @[
                       @"https://ss2.baidu.com/-vo3dSag_xI4khGko9WTAnF6hhy/super/whfpf%3D425%2C260%2C50/sign=a4b3d7085dee3d6d2293d48b252b5910/0e2442a7d933c89524cd5cd4d51373f0830200ea.jpg",
                       @"https://ss0.baidu.com/-Po3dSag_xI4khGko9WTAnF6hhy/super/whfpf%3D425%2C260%2C50/sign=a41eb338dd33c895a62bcb3bb72e47c2/5fdf8db1cb134954a2192ccb524e9258d1094a1e.jpg",
                       @"http://c.hiphotos.baidu.com/image/w%3D400/sign=c2318ff84334970a4773112fa5c8d1c0/b7fd5266d0160924c1fae5ccd60735fae7cd340d.jpg"
                       ];
    NSArray *array2 = @[@"1.jpg", @"2.jpg", @"3.jpg", @"4.jpg", @"5.jpg"];
//    _cycleView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, kNavigationBarHeight, UISCREENWIDTH, 55) imageURLStringsGroup:array];
    _cycleView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, kNavigationBarHeight, UISCREENWIDTH, 55) delegate:self placeholderImage:[UIImage imageNamed:@"1.jpg"]];
    _cycleView.imageURLStringsGroup = array;
//    _cycleView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, kNavigationBarHeight, UISCREENWIDTH, 55) shouldInfiniteLoop:YES imageNamesGroup:array2];
//    _cycleView.contentMode = UIViewContentModeScaleToFill;
//    _cycleScrollView.delegate = self;
    _cycleView.autoScrollTimeInterval = 2.0f;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.view addSubview:_cycleView];
}

- (void)setupCollectionView{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, _cycleView.bottom, UISCREENWIDTH, self.view.height - kNavigationBarHeight - _cycleView.height - self.tabBarController.tabBar.height) collectionViewLayout:flowLayout];
    [_collectionView registerClass:[HomePageCollectionViewCell class] forCellWithReuseIdentifier:homepageCollectionCellName];
    [_collectionView registerClass:[HomePageCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:homepageCollectionReusableName];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_collectionView];
}

- (void)fakeValue{
    NSMutableArray *array1 = [NSMutableArray arrayWithCapacity:5];
    for (int i = 0; i < 10; i ++) {
        HomePageModel *model = [[HomePageModel alloc] init];
        model.title = @"广州市朝秀区盘福路79号620、621（整体拍）";
        model.itemImage = [UIImage imageNamed:@"bg.jpg"];
        model.price = @"31802.78";
        model.selected = YES;
        model.starring = @"3626";
        
        NSDate *date = [[NSDate alloc] initWithTimeIntervalSinceNow:2430];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = timeFormatter;
        model.boundTime = [formatter stringFromDate:date];
        
        [array1 addObject:model];
    }
    _dataArr = array1;
}

#pragma mark - Bar Button Item Action

/**
 *  @author GripMeMory, 15-12-01 14:12:19
 *
 *  leftbarbutton item action
 *
 *  @param bbi the barbuttonitem responds the call
 */
- (void)leftBarButtonItemClick:(UIBarButtonItem *)bbi{
    
    //Init the content View in the Popover view
    
    _tbc = [[UITableViewController alloc] initWithStyle:UITableViewStylePlain];
    _tbc.tableView.tag = 101;
    
    _tbc.tableView.dataSource = self;
    _tbc.tableView.delegate = self;
    
    _tbc.tableView.backgroundColor = [UIColor darkGrayColor];
    _tbc.tableView.scrollEnabled = NO;
    _tbc.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tbc.preferredContentSize = CGSizeMake(130, 250);
    [_tbc.tableView registerClass:[PopSelectionCell class] forCellReuseIdentifier:SelectionCellName];
    
    //Popover appearance
    WYPopoverBackgroundView *appearance = [WYPopoverBackgroundView appearance];
    [appearance setInnerCornerRadius:0];
    [appearance setOuterCornerRadius:0];
    [appearance setOuterShadowOffset:CGSizeZero];
    [appearance setViewContentInsets:UIEdgeInsetsZero];
    [appearance setBorderWidth:0];

    //Init the popover view controller
    _popover = [[WYPopoverController alloc] initWithContentViewController:_tbc];
    
    //Binding the Action with the barbuttonitem
    [_popover presentPopoverFromBarButtonItem:bbi permittedArrowDirections:WYPopoverArrowDirectionUp animated:YES];
}

- (void)rightBarButtonItemClick:(UIBarButtonItem *)bbi{
    
    NSLog(@"消息");
    
    MessageCenterViewController *mvc = [[MessageCenterViewController alloc] init];
    [self.navigationController pushViewController:mvc animated:NO];
    
}

- (void)titleViewClick:(UITapGestureRecognizer *)tap{
    HomePageSearchViewController *hpc = [[HomePageSearchViewController alloc] init];
    [self.navigationController pushViewController:hpc animated:NO];
}

#pragma mark - Refresh Action

/**
 *  @author GripMeMory, 15-12-01 14:12:53
 *
 *  Refresh the tableView
 */
- (void)refreshAction{
    [self.tableView reloadData];
    [self.tableView.mj_header endRefreshing];
}

#pragma mark - Textfield Delegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    HomePageSearchViewController *search = [[HomePageSearchViewController alloc] init];
    [self.navigationController pushViewController:search animated:NO];
    return NO;
}

#pragma mark - CollectionView DataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 5;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 2;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    HomePageCollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:homepageCollectionReusableName forIndexPath:indexPath];
    if (!header) {
        header = [[HomePageCollectionReusableView alloc] init];
    }
    [header configureTitleWithString:_array[indexPath.section]];
    return header;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    HomePageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:homepageCollectionCellName forIndexPath:indexPath];
    if (!cell) {
        cell = [[HomePageCollectionViewCell alloc] init];
    }
    
    [cell configureCellWithTwoPicsModel:_dataArr[indexPath.row]];
    
    return cell;
}

#pragma mark - CollectionView FlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGSize size = CGSizeMake((UISCREENWIDTH - 3 * 15) / 2, 410 / 2);
    return size;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(5, 15, 5, 15);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(UISCREENWIDTH, 30);
}

#pragma mark - CollectionView Delegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    OfferSiteViewController *osvc = [[OfferSiteViewController alloc] init];
    [self.navigationController pushViewController:osvc animated:NO];
}

#pragma mark - TableView DataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _selectionArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.tag == 101) {
        PopSelectionCell *cell = [tableView dequeueReusableCellWithIdentifier:SelectionCellName forIndexPath:indexPath];
        if (!cell) {
            cell = [[PopSelectionCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SelectionCellName];
        }
        [cell configureCellWithModel:_selectionArr[indexPath.row]];
        return cell;
    }else{
        return nil;
    }
}

#pragma mark - TableView Delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.tag == 101 || tableView.tag == 102) {
        return 50;
    }
    return kHomePageCellHeight;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.tag == 101) {
        ChannelViewController *cvc = [[ChannelViewController alloc] init];
        [self.navigationController pushViewController:cvc animated:NO];
        [_popover dismissPopoverAnimated:NO];
    }
}

@end
